package com.streambolics.data;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

public class PersistentObject
{
    private PersistenceManager _Database;

    /**
     * The first object of the appropriate type that matches a simple equality.
     * 
     * @param <T>
     *            The type of objects to return.
     * @param aDatabase
     *            The database
     * @param aType
     *            The type of objects to return.
     * @param aField
     *            The name of the field to match.
     * @param aValueType
     *            The type of aField.
     * @param aValue
     *            The value to match.
     * @return The first object found that matches the equality. If multiple
     *         objects are found, one of the objects is returned. If no object
     *         is found, null is returned.
     */

    protected static <T> T getFirstWhere (PersistenceManager aDatabase, Class<T> aType, String aField, String aValueType, Object aValue)
    {
        List<T> l = getListWhere (aDatabase, aType, aField, aValueType, aValue);
        if (l.size () >= 1)
        {
            return l.get (0);
        }
        else
        {
            return null;
        }
    }

    /**
     * A list of objects from the database that match a simple equality.
     * 
     * @param <T>
     *            The type of objects to return.
     * @param aDatabase
     *            The database
     * @param aType
     *            The type of objects to return.
     * @param aField
     *            The name of the field to match.
     * @param aValueType
     *            The type of aField.
     * @param aValue
     *            The value to match.
     * @return The list of objects of type aType, where the field aField equals
     *         aValue.
     */

    @SuppressWarnings("unchecked")
    protected static <T> List<T> getListWhere (PersistenceManager aDatabase, Class<T> aType, String aField, String aValueType, Object aValue)
    {
        String qt = "select from " + aType.getName () + " where " + aField + "==p_arg";
        Query q = aDatabase.newQuery (qt);
        q.declareParameters (aValueType + " p_arg");
        return (List<T>) q.execute (aValue);
    }

    /**
     * The database attached to this object.
     * 
     * @return
     */

    protected PersistenceManager getDatabase ()
    {
        return _Database;
    }

    public void setDatabase (PersistenceManager aDatabase)
    {
        _Database = aDatabase;
    }
}
